# receive the word and store it into db
# return nothing

# receive the data as a series of segments
# use 'id' as the uuid of segment
# use 'sq' as the sequence number
# use 'ct' as the name of content
# use 'op' as the end of segments, value=end


import cgi, cgitb
import os, sys



sys.path.append(os.path.join(os.path.dirname(__file__), 'lib'))

import utils
from entity import Data
from entity import Segment

from google.appengine.ext import db

from datetime import datetime


  
  


def checkParameter(uuid, seqnum):
  # check parameters
  if uuid is None or seqnum is None or content is None:
    print "Content-Type: text/plain"
    print 'Status: 404 Not Found'
    print ""
    print "parameter is none."
    exit(-1)

  # valid the "seq" must be a number
  if not seqnum.isdigit():
    print "Content-Type: text/plain"
    print 'Status: 404 Not Found'
    print ""
    print "sequence number is not a number."
    exit(-1)


# create segment object & save
def addNewSegment(uuid,seqnum,content):
  segment = Segment(uuid=uuid,seq=int(seqnum),datetime=datetime.utcnow())
  segment.content = db.Text(content, encoding="utf-8")
  segment.put()
  return segment



# =============business logic===============

# get parameters from url

form = cgi.FieldStorage()

uuid = form.getvalue("id")
seqnum = form.getvalue("sq")
content = form.getvalue("ct")
op = form.getvalue("op")
tzoffset = form.getvalue("tzoffset")

print "Content-Type: text/plain"
print ""

# list all data in db
if op == "list":
  for segment in Segment.all():
    print str(segment)
    print "--------------------"

  print "Total:",Segment.all().count()
  exit(0)




# valid url parameter
checkParameter(uuid, seqnum)

segment = addNewSegment(uuid,seqnum,content)

if op == "end":
  data = utils.buildDataById(uuid);
  print utils.jsonDataAsList(data,tzoffset)
else:
  print segment.seq



